package com.lishe.lishe.lishe.module.mall.fragment;

import android.content.Context;
import android.content.Intent;
import android.graphics.Paint;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.SpannableString;
import android.text.style.ImageSpan;
import android.util.SparseArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.lishe.base.view.CenterAlignImageSpan;
import com.lishe.lishe.Imageloader.ImageLoaderUtils;
import com.lishe.lishe.R;
import com.lishe.base.common.base.BaseFragment;
import com.lishe.lishe.lishe.common.Globals;
import com.lishe.lishe.lishe.module.auth.activity.AuthActivity;
import com.lishe.lishe.lishe.module.mall.activity.CheckGoodsImgActivity;
import com.lishe.lishe.lishe.module.mall.activity.GoodsDetailActivity;
import com.lishe.lishe.lishe.module.mall.activity.WhatsIntegralActivity;
import com.lishe.lishe.lishe.module.mall.bean.CouponObject;
import com.lishe.lishe.lishe.module.mall.bean.MallGoods;
import com.lishe.lishe.lishe.module.mall.bean.MoreItemBean;
import com.lishe.lishe.lishe.module.mall.bean.SkuObject;
import com.lishe.lishe.lishe.module.mall.event.GoodsDetailRefreshEvent;
import com.lishe.lishe.lishe.module.mall.http.HttpMall;
import com.lishe.lishe.lishe.module.mall.view.CouponListDialog;
import com.lishe.lishe.lishe.module.mall.view.GoodsParameterDialog;
import com.lishe.lishe.lishe.module.mall.view.GoodsPromotionDialog;
import com.lishe.lishe.lishe.utils.LoadingUtils;
import com.lishe.lishe.lishe.utils.LogUtil;
import com.lishe.lishe.lishe.widget.GoodsProDialog;
import com.lishe.lishe.lishe.module.mall.view.snapscrollview.GoodsDetailPage;
import com.lishe.lishe.lishe.module.mall.view.snapscrollview.GoodsInfoPage;
import com.lishe.lishe.lishe.module.mall.view.snapscrollview.SnapPageLayout;
import com.lishe.lishe.retrofit.DataResponseListener;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.youth.banner.Banner;
import com.youth.banner.BannerConfig;
import com.youth.banner.listener.OnBannerListener;
import com.youth.banner.loader.ImageLoader;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

import cz.msebera.android.httpclient.Header;
import cz.msebera.android.httpclient.util.TextUtils;

/**
 * Created by shino on 2017/9/19.
 * & Bin
 * 商品详情页
 */
public class GoodsDetailFragent extends BaseFragment implements View.OnClickListener, OnBannerListener {

    //商品状态
    public static final int ONSALE = -1;
    public static final int INSTOCK = -2;
    private int mGoodStatus = ONSALE;
    private View mErrorLayout;
    private WebView mBottomWeb;
    private GoodsDetailPage bottomPage;
    private View mCouponLayout;
    private View mCouponLine;

    public int getGoodStatus() {
        return mGoodStatus;
    }

    private String mDetailUrl = Globals.LISHE_URL + "goods/details/itemId/";
    private LinearLayout goodsListLayout;
    private TextView name;
    private TextView discount;
    private TextView mTvPrice;
    private TextView mTvMktPrice;
    private String itemId;

    private ArrayList<String> mBannerImages = new ArrayList<>();//轮播的图片地址
    private LinkedList<SkuObject> skus = new LinkedList<>();//skus
    private LinkedList<CouponObject> mCouponList = new LinkedList<>();//优惠券
    private MallGoods mallGoods = new MallGoods();//
    private Banner mBanner;
    private TextView mIntegral;
    private View mPromotionLayout;
    private TextView mTvPromotionText;
    private SnapPageLayout mSnapPageLayout;
    private View mScrollLogo;
    private TextView mScrollTip;
    private TextView mCoupon1, mCoupon2;

    public static GoodsDetailFragent newInstance(String itemId) {
        GoodsDetailFragent fragment = new GoodsDetailFragent();
        Bundle bundle = new Bundle();
        bundle.putString("itemId", itemId);
        fragment.setArguments(bundle);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
        itemId = getArguments().getString("itemId");
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.activity_goods_detail, null);
        //init 外层滑动切换布局
        mErrorLayout = view.findViewById(R.id.error_layout);
        view.findViewById(R.id.error_retry).setOnClickListener(this);
        mSnapPageLayout = view.findViewById(R.id.flipLayout);
        mSnapPageLayout.setPageChangeListener(new SnapPageLayout.PageChangeListener() {
            @Override
            public void changeTo1() {}

            @Override
            public void changeTo2() {}

            //2 -> 1 已切换
            @Override
            public void HadChangedTo1() {
                ((GoodsDetailActivity) getActivity()).resetTitle(0);
                mScrollTip.setText(R.string.go_on_up);
                mScrollLogo.setBackgroundResource(R.mipmap.up);
//                mBottomWeb.setVisibility(View.GONE);
            }

            //1 -> 2  已切换
            @Override
            public void HadChangedTo2() {
                ((GoodsDetailActivity) getActivity()).resetTitle(1);
                mScrollTip.setText(R.string.go_on_down);
                mScrollLogo.setBackgroundResource(R.mipmap.down);
                mBottomWeb.setVisibility(View.VISIBLE);
            }
        });
        View topView = inflater.inflate(R.layout.layout_goods_info_page, null);
        final GoodsInfoPage topPage = new GoodsInfoPage(getActivity(), topView);
        View bottomView = inflater.inflate(R.layout.layout_goods_detail_page, null);
        mBottomWeb = bottomView.findViewById(R.id.web);
        bottomPage = new GoodsDetailPage(getActivity(), bottomView, new GoodsDetailPage.UpClicker() {
            @Override
            public void onUpClick() {
                topPage.go2top();
                mSnapPageLayout.snapToPrev();
            }
        });
        LogUtil.i("url", mDetailUrl + itemId);
        bottomPage.setWebView(mDetailUrl + itemId);
        mSnapPageLayout.setSnapPages(topPage, bottomPage);

        initView(topView);
        getData();
        view.setOnTouchListener(this);
        return view;
    }

    private void initView(View v) {
        mBanner = v.findViewById(R.id.banner);
        //设置轮播图片间隔时间
        mBanner.setDelayTime(5000);
        //banner点击事件
        mBanner.setOnBannerListener(this);
        //设置banner样式
        mBanner.setBannerStyle(BannerConfig.NUM_INDICATOR);

        goodsListLayout = v.findViewById(R.id.goods_list_layout);
        name = v.findViewById(R.id.name);
        discount = v.findViewById(R.id.discount);
        mTvPrice = v.findViewById(R.id.price);
        mTvMktPrice = v.findViewById(R.id.mkt_price);
        mIntegral = v.findViewById(R.id.integral);
        //促销
        mTvPromotionText = v.findViewById(R.id.promotion_text);
        mPromotionLayout = v.findViewById(R.id.promotion_layout);
        mPromotionLayout.setOnClickListener(this);
        //滑动切换
        mScrollTip = v.findViewById(R.id.scroll_tip);
        mScrollLogo = v.findViewById(R.id.scroll_logo);
        //优惠券
        mCoupon1 = v.findViewById(R.id.coupon1);
        mCoupon2 = v.findViewById(R.id.coupon2);
        mCouponLine = v.findViewById(R.id.couponLine);
        mCouponLayout = v.findViewById(R.id.couponlayout);
        mCouponLayout.setOnClickListener(this);

        v.findViewById(R.id.whats_integral).setOnClickListener(this);
        v.findViewById(R.id.hadchose_layout).setOnClickListener(this);
        v.findViewById(R.id.parameter_layout).setOnClickListener(this);
    }

    private void getData() {
        if (itemId != null) {
            LoadingUtils.createLoadingDialog(getActivity(), "请稍后...", true);
            HttpMall.getGoodsDetailInfo(Globals.getToken(), itemId, mDataResponse);
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(GoodsDetailRefreshEvent event) {
        getData();
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.couponlayout:
                if (TextUtils.isEmpty(Globals.getToken())) {
                    Intent i = new Intent(getActivity(), AuthActivity.class);
                    i.putExtra("from", "GoodsDetail");
                    startActivity(i);
                    return;
                }
                new CouponListDialog(context, mCouponList).show();
                break;
            case R.id.error_retry:
                mErrorLayout.setVisibility(View.GONE);
                getData();
                bottomPage.setWebView(mDetailUrl + itemId);
                break;
            case R.id.whats_integral://什么是积分
                startActivity(new Intent(getActivity(), WhatsIntegralActivity.class));
                break;
            case R.id.promotion_layout://促销弹窗
                new GoodsPromotionDialog(context, mallGoods.getDiscountList()).show();
                break;
            case R.id.hadchose_layout://已选弹窗
                if (TextUtils.isEmpty(Globals.getToken())) {
                    Intent i = new Intent(getActivity(), AuthActivity.class);
                    i.putExtra("from", "GoodsDetail");
                    startActivity(i);
                    return;
                }
                GoodsDetailActivity mActivity = (GoodsDetailActivity) getActivity();
                mActivity.showProDialog(mallGoods, GoodsProDialog.FROM_HADCHOSE);
                break;
            case R.id.parameter_layout://参数弹窗
                new GoodsParameterDialog(context, mallGoods.getItem_id(),
                        String.format("%.2f", Float.parseFloat(mallGoods.getWeight())) + "kg",
                        mallGoods.getBrand()).show();
                break;
        }
    }

    @Override
    public void onStart() {
        super.onStart();
        //Banner增加体验
        mBanner.startAutoPlay();
    }

    @Override
    public void onStop() {
        super.onStop();
        //Banner增加体验
        mBanner.stopAutoPlay();
    }

    /**
     * UI数据初始化
     */
    private void initUI() {
        //Banner
        mBanner.setImages(mBannerImages).setImageLoader(new ImageLoader() {
            @Override
            public void displayImage(Context context, Object path, ImageView imageView) {
                //imageView.setAdjustViewBounds(true);
                ImageLoaderUtils.displayImage(GoodsDetailFragent.this, path.toString(), imageView, R.drawable.defalut_img);
            }
        }).start();

        mIntegral.setText(String.format("%.0f", Double.parseDouble(mallGoods.getPrice()) * 100));
        mTvPrice.setText("¥" + mallGoods.getPrice());
        CenterAlignImageSpan imageSpan = null;
        SpannableString sp = new SpannableString(mallGoods.getTitle());
        if ("43".equals(mallGoods.getShop_id())){
            //获取一张图片
            imageSpan = new CenterAlignImageSpan(getActivity(),R.mipmap.home_ic_wy);
        } else if ("10".equals(mallGoods.getShop_id())){
            imageSpan = new CenterAlignImageSpan(getActivity(),R.mipmap.home_ic_jd);
        }
        //居中对齐imageSpan
        sp.setSpan(imageSpan, 0, 1, ImageSpan.ALIGN_BASELINE);
        name.setText(sp);
        /*if (mallGoods.getDiscount() == 0) {
            discount.setVisibility(View.GONE);
        } else {
            discount.setVisibility(View.VISIBLE);
            discount.setText(String.format("%.1f", mallGoods.getDiscount() * 10) + "折");
        }*/
        // 原价
        if (Double.parseDouble(mallGoods.getMkt_price()) > 0) {
            mTvMktPrice.setVisibility(View.VISIBLE);
            mTvMktPrice.setText("¥" + mallGoods.getMkt_price());
        } else {
            mTvMktPrice.setVisibility(View.GONE);
        }
        mTvMktPrice.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG);

        //促销
        if (mallGoods.getDiscountList().size() > 0) {
            mPromotionLayout.setVisibility(View.VISIBLE);
            mTvPromotionText.setText(mallGoods.getDiscountList().get(0).getTitle());
        } else {
            mPromotionLayout.setVisibility(View.GONE);
        }

        mCoupon1.setVisibility(View.GONE);
        mCoupon2.setVisibility(View.GONE);
        //优惠券
        if (mCouponList.size() == 0) {
            mCouponLine.setVisibility(View.GONE);
            mCouponLayout.setVisibility(View.GONE);
        }
        if (mCouponList.size() >= 1) {
            mCouponLine.setVisibility(View.VISIBLE);
            mCouponLayout.setVisibility(View.VISIBLE);
            mCoupon1.setText(mCouponList.get(0).getCoupon_rule_detail());
            mCoupon1.setVisibility(View.VISIBLE);
        }
        if (mCouponList.size() >= 2) {
            mCoupon2.setText(mCouponList.get(1).getCoupon_rule_detail());
            mCoupon2.setVisibility(View.VISIBLE);
        }
    }

   /* public String getCouponMsg(int position) {
        switch (mCouponList.get(position).getCoupon_rule()) {  //优惠券规则
            //1：满减，2：满折，3：满免邮，4：直减
            case "1":
                return "满" + mCouponList.get(position).getCoupon_over() + "元减" + mCouponList.get(position).getCoupon_decrease();

            case "2":
                return "满" + mCouponList.get(position).getCoupon_over() + "元打" + mCouponList.get(position).getCoupon_discount() + "折";

            case "3":
                return "满" + mCouponList.get(position).getCoupon_over() + "元包邮";

            case "4":
                return "直减" + mCouponList.get(position).getCoupon_decrease() + "元";

        }
        return "";
    }*/

    public MallGoods getMallObject() {
        return mallGoods;
    }

    /**
     * 商品详情
     */
    AsyncHttpResponseHandler mDataResponse = new AsyncHttpResponseHandler() {
        @Override
        public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
            String result = new String(responseBody);
            LogUtil.completeLog("商品详情", result);
            try {
                JSONObject json = new JSONObject(result);
                if (0 == json.optInt("errcode") && 100 == json.optInt("result")) {
                    JSONObject dataObject = json.optJSONObject("data");
                    JSONObject itemInfo = dataObject.optJSONObject("itemInfo");
                    mallGoods.setApprove_status(itemInfo.optString("approve_status"));
                    mallGoods.setShop_id(itemInfo.optString("shop_id"));
                    JSONObject brand_id = itemInfo.optJSONObject("brand_id");
                    if (brand_id == null) {
                        mallGoods.setBrand("");
                    } else {
                        mallGoods.setBrand(brand_id.optString("brand_name"));
                    }
                    mallGoods.setMkt_price(itemInfo.optString("mkt_price"));
                    mallGoods.setPrice(itemInfo.optString("price"));
                    mallGoods.setTitle(itemInfo.optString("title"));
                    mallGoods.setWeight(itemInfo.optString("weight"));
                    mallGoods.setItem_id(itemInfo.optString("item_id"));
                    mallGoods.setImage_default_id(itemInfo.optString("image_default_id"));
                    mallGoods.setJd_ids(itemInfo.optString("jd_sku"));
                    mallGoods.setCat_id(itemInfo.optString("cat_id"));
                    JSONArray itemList = dataObject.optJSONArray("itemList");
                    JSONArray skuList = dataObject.optJSONArray("skuList");
                    JSONArray couponList = dataObject.optJSONArray("couponList");
                    skus.clear();
                    for (int i = 0; i < skuList.length(); i++) {
                        JSONObject skuListObject = skuList.optJSONObject(i);
                        SkuObject skuObject = new SkuObject();
                        if (i == 0) {
                            mallGoods.setKucun(skuListObject.optString("store"));
                            mallGoods.setSku_id(skuListObject.optString("sku_id"));
                            //规格spec_info，空时显示默认
//                            if (!skuListObject.optString("spec_info").equals("") && !skuListObject.optString("spec_info").equals("null")) {
                            skuObject = JSON.parseObject(skuListObject.toString(), SkuObject.class);
                            skus.add(skuObject);
//                            }
                        } else {
                            skuObject = JSON.parseObject(skuListObject.toString(), SkuObject.class);
                            skus.add(skuObject);
                        }
                    }

                    //优惠券
                    if (couponList != null) {
                        mCouponList.clear();
                        for (int i = 0; i < couponList.length(); i++) {
                            JSONObject couponListObject = couponList.optJSONObject(i);
                            CouponObject object = JSON.parseObject(couponListObject.toString(), CouponObject.class);
                            mCouponList.add(object);
                        }
                    }

                    //促销信息
                    JSONArray discountList = dataObject.optJSONArray("discount");
                    SparseArray<MallGoods.Discount> promotions = new SparseArray<>();//促销信息数组
                    for (int i = 0; i < discountList.length(); i++) {
                        JSONObject object = discountList.optJSONObject(i);
                        MallGoods.Discount clazz = new MallGoods.Discount(object.optString("title"));
                        promotions.put(i, clazz);
                    }
                    mallGoods.setDiscountList(promotions);

                    JSONArray new_list_images = itemInfo.optJSONArray("new_list_images");
                    mBannerImages.clear();
                    for (int i = 0; i < new_list_images.length(); i++) {
                        mBannerImages.add(new_list_images.optString(i));
                    }

                    //更新UI数据
                    initUI();
                    getMoreItems(mallGoods.getItem_id());
                    //改变MallGoodsAcivity的底部按钮
                    initStatus(mallGoods.getApprove_status());
                    ((GoodsDetailActivity) getActivity()).resetGoodsStatus(mGoodStatus);
                    ((GoodsDetailActivity) getActivity()).showBottom(true);
                    mSnapPageLayout.setVisibility(View.VISIBLE);
                } else {
                    String msg = json.optString("msg");
                    toast(msg);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            LoadingUtils.closeDialog();
        }

        @Override
        public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
            LoadingUtils.closeDialog();
            if (isAdded()) {
                mSnapPageLayout.setVisibility(View.GONE);
                mErrorLayout.setVisibility(View.VISIBLE);
                ((GoodsDetailActivity) getActivity()).showBottom(false);
            }
        }
    };

    /**
     * 获取更多精选商品
     */
    public void getMoreItems(String item_id) {
        HttpMall.getMoreItems(item_id, new DataResponseListener<MoreItemBean>() {
            @Override
            public void onSuccess(MoreItemBean data) {
                //可能喜欢
                goodsListLayout.removeAllViews();
                for (final MoreItemBean.DataBean bean : data.getData()) {
                    if (getActivity()!=null){
                        View goodsLayout = getActivity().getLayoutInflater().inflate(R.layout.item_mall_scroll, null);
                        ImageView goods_img = goodsLayout.findViewById(R.id.goods_img);
                        TextView goods_name = goodsLayout.findViewById(R.id.goods_name);
                        TextView price = goodsLayout.findViewById(R.id.price);
                        //Log.e("url", mall.getImage_default_id());
                        ImageLoaderUtils.displayImage(GoodsDetailFragent.this, bean.getImage_default_id(), goods_img, R.drawable.defalut_img);
                        goods_name.setText(bean.getTitle());
                        goodsLayout.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View view) {
                                GoodsDetailActivity.jump(getActivity(), bean.getItem_id());
                            }
                        });
                        price.setText("¥" + bean.getPrice());
                        goodsListLayout.addView(goodsLayout);
                    }
                }
            }

            @Override
            public void onFail(String failMessage) {
            }

            @Override
            public void onError(Throwable e) {
            }
        });
    }

    /**
     * title点击 切换逻辑
     *
     * @param index
     */
    public void scrollTo(int index) {
        if (mSnapPageLayout.getVisibility() == View.GONE) {
            return;
        }

        if (index == 0) {
            mSnapPageLayout.snapToNext();
        } else if (index == 1) {
            mSnapPageLayout.snapToPrev();
        }
    }

    public List<SkuObject> getSkus() {
        return skus;
    }

    private void initStatus(String str) {
        if ("onsale".equals(str)) {
            mGoodStatus = ONSALE;
        } else if ("instock".equals(str)) {
            mGoodStatus = INSTOCK;
        }
    }

    @Override
    public void OnBannerClick(int position) {
        Intent i = new Intent(getActivity(), CheckGoodsImgActivity.class);
        i.putExtra(CheckGoodsImgActivity.CURRENT_INDEX, position);
        i.putStringArrayListExtra(CheckGoodsImgActivity.IMG_LIST, mBannerImages);
        startActivity(i);
    }

}